package com.base.system.base.db.specifications;

import cn.hutool.core.util.StrUtil;

import javax.persistence.criteria.*;

/**
 * & 与运算
 *
 * @param <T>
 */
public class IntersectionSpecification<T> extends AbstractSpecification<T> {
    private static final long serialVersionUID = 6690291922287079277L;
    private final String property;
    private final Object patterns;
    private String dataProperty = null;

    /**
     * @param property     查询字段
     * @param joinType
     * @param v            条件值
     * @param dataProperty 数据库中以定义的基准值字段
     */
    public IntersectionSpecification(String property, JoinType joinType, Object v, String dataProperty) {
        this.property = property;
        patterns = v;
        this.joinType = joinType;
        this.dataProperty = dataProperty;
    }

    public IntersectionSpecification(String property, JoinType joinType, Object v) {
        this.property = property;
        patterns = v;
        this.joinType = joinType;
    }

    @Override
    public Predicate toPredicate(Root<T> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
        From from = getFrom(property, root);
        String attr = getProperty(property);
        Expression<Integer> pd = null;
        if (StrUtil.isEmpty(dataProperty)) pd = cb.function("pd", Integer.class, cb.literal(patterns), from.get(attr));
        else {
            From from1 = getFrom(dataProperty, root);
            String attr1 = getProperty(dataProperty);
            pd = cb.function("pd", Integer.class, cb.literal(patterns), from.get(attr), from1.get(attr1));
        }

        return cb.gt(pd, 0);
    }
}
